package com.jike.jkgame;

import java.io.IOException;

import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;

import com.jike.jkgame.data.Preferences;
import com.jike.jkgame.data.UserStatus;
import com.jike.jkgame.exception.EncodingException;
import com.jike.jkgame.exception.NetworkErrorException;
import com.jike.jkgame.network.MessageFactory;
import com.jike.jkgame.network.NetworkUtilis;
import com.jike.jkgame.network.ResponseHandler;
import com.jike.jkgame.network.ServerConfig;

public class LoginActivity extends Activity implements OnClickListener {

	private EditText mUserNameEt;
	private EditText mPasswordEt;
	private TextView mErrorTv;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.login_layout);

		mUserNameEt = (EditText) findViewById(R.id.et_username);
		mPasswordEt = (EditText) findViewById(R.id.et_password);
		mErrorTv = (TextView) findViewById(R.id.tv_error_msg);

		findViewById(R.id.btn_login).setOnClickListener(this);
		findViewById(R.id.btn_signup).setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.btn_login: {
			String userName = mUserNameEt.getText().toString();
			String password = mPasswordEt.getText().toString();

			if (checkInput(userName, password)) {

				if (login(userName, password)) {
					Preferences pref = Preferences.get();
					pref.putString(Preferences.Keys.UserName, userName);
					pref.putString(Preferences.Keys.Password, password);
					setResult(1);
					finish();
				}
			}

			break;
		}
		case R.id.btn_signup: {
			String userName = mUserNameEt.getText().toString();
			String password = mPasswordEt.getText().toString();
			// userName = "jing@jike.com";
			// password = "123456";
			// signup(userName, password);
			if (checkInput(userName, password)) {
				if (signup(userName, password) ) {
					if (login(userName, password)) {
						Preferences pref = Preferences.get();
						pref.putString(Preferences.Keys.UserName, userName);
						pref.putString(Preferences.Keys.Password, password);
						setResult(1);
						finish();
					}
				}
			}

			break;
		}
		default:
			break;
		}
	}

	private boolean signup(String name, String password) {

		try {

			JSONObject params = MessageFactory.createRegistMessage(name,
					password);

			String response = NetworkUtilis.getHttpString(
					ServerConfig.getStaticLoginServer(), params);

			String error = ResponseHandler.getSignupError(response);

			if (error == null) {
				return true;
			} else {
				mErrorTv.setText(error);
			}

		} catch (NetworkErrorException e) {
			e.printStackTrace();
		} catch (EncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return false;
	}

	/**
	 * 尝试自动登陆，使用保存的用户名和密码
	 * 
	 * @return true 登陆成功 false 登陆失败
	 */
	public boolean autoLogin() {
		Preferences pref = Preferences.get();
		String username = pref.getString(Preferences.Keys.UserName);
		String password = pref.getString(Preferences.Keys.Password);

		if (username == null || password == null) {
			return false;
		} else {
			return login(username, password);
		}

	}

	private boolean login(String userName, String password) {
		try {
			JSONObject params = MessageFactory.createLoginMessage(userName,
					password);

			String response = NetworkUtilis.getHttpString(
					ServerConfig.getStaticLoginServer(), params);

			String error = ResponseHandler.getLoginError(response);

			if (error == null) {
				// 处理返回的消息
				try {
					JSONObject json = new JSONObject(response);
					long id = json.getLong("id");
					UserStatus.get().setUid(id);
					return true;
				} catch (JSONException e) {
					e.printStackTrace();
				}

			} else {
				mErrorTv.setText(error);
			}

		} catch (NetworkErrorException e) {
			e.printStackTrace();
		} catch (EncodingException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		return false;
	}

	private boolean checkInput(String userName, String password) {

		StringBuilder errorSb = new StringBuilder();

		String error = checkUserName(userName);

		if (error != null) {
			errorSb.append(error);
		}

		error = checkPassword(password);
		if (error != null) {
			if (errorSb.length() > 0) {
				errorSb.append('\n');
			}
			errorSb.append(error);
		}

		if (errorSb.length() > 0) {
			mErrorTv.setText(errorSb.toString());
			return false;
		}
		mErrorTv.setText("");
		return true;
	}

	private String checkUserName(String name) {

		if (name == null || name.length() == 0) {
			return getString(R.string.error_username_empty);
		}

		if (!name.matches(".*@.*")) {
			return getString(R.string.error_username_noemail);
		}

		// if (name.length() < 4) {
		// return getString(R.string.error_username_length);
		// }
		//
		// if (!name.matches("\\w*")) {
		// return getString(R.string.error_username_character);
		// }

		return null;

	}

	private String checkPassword(String pass) {
		if (pass == null || pass.length() < 3) {
			return getString(R.string.error_password_length);
		}

		return null;
	}
}
